package org.mspring.mlog.web.admin;

import org.apache.commons.lang3.StringUtils;
import org.mspring.mlog.common.exception.OperateException;
import org.mspring.mlog.entity.UserEntity;
import org.mspring.mlog.service.UserEntityService;
import org.mspring.mlog.support.TabItem;
import org.mspring.mlog.web.BaseAdminController;
import org.mspring.nbee.web.support.WebContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author Gao Youbo
 * @since 2015-11-22 14:41
 */
@Controller
@RequestMapping("/admin/user")
@TabItem(item = "200105")
public class UserController extends BaseAdminController {
    private UserEntityService userEntityService;

    @RequestMapping("/edit")
    @TabItem(item = "200105005")
    public String edit(WebContext context, Model model) {
        UserEntity user = getCurrentUser();
        user = userEntityService.findById(user.getId());
        model.addAttribute("user", user);
        return "/admin/user/edit";
    }

    @RequestMapping("/edit/do")
    public String doEdit(WebContext context, Model model) {
        String username = context.getRequiredParam("username");
        String nickname = context.getRequiredParam("nickname");
        String email = context.getRequiredParam("email");

        UserEntity user = getCurrentUser();
        user = userEntityService.findById(user.getId());

        user.setUsername(username);
        user.setNickname(nickname);
        user.setEmail(email);

        userEntityService.update(user);
        return "redirect:/admin/user/edit";
    }


    @RequestMapping("/password")
    @TabItem(item = "200105010")
    public String password(WebContext context, Model model) {
        return "/admin/user/password";
    }

    @RequestMapping("/password/change")
    public String changePassword(WebContext context, Model model) {
        String oldPassword = context.getRequiredParam("oldPassword");
        String newPassword = context.getRequiredParam("newPassword");
        String rePassword = context.getRequiredParam("rePassword");

        if (!StringUtils.equals(newPassword, rePassword)) {
            throw new OperateException("两次输入密码不一致.");
        }

        UserEntity user = getCurrentUser();

        boolean validatePwd = securityService.validatePassword(oldPassword, user.getPassword());
        if (!validatePwd) {
            throw new OperateException("密码验证失败,请确认旧密码是否正确.");
        }

        String encodeNewPassword = securityService.encodePassword(newPassword);
        user.setPassword(encodeNewPassword);
        userEntityService.update(user);
        return "redirect:/admin/logout";
    }


    @Autowired
    public void setUserEntityService(UserEntityService userEntityService) {
        this.userEntityService = userEntityService;
    }
}
